<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Length
 *
 * @author chaporgin_a
 */
class VA_Form_Validator_Length extends VA_Form_Validator {
    protected $min = null;
    protected $max = null;
    protected $messages = array(
      'Введите от %d до %d символов'
      , 'Нельзя вводить более %d символов'
      , 'Должно быть не менее %d символов'
      );
    protected function provideErrorMessage($value){
      
      if(($this->min > -1) && ($this->max > -1))
        return sprintf($this->messages[0], $this->min, $this->max);
      elseif(($this->min > -1))
        return sprintf($this->messages[2], $this->min);
      elseif(($this->max > -1))
        return sprintf($this->messages[1], $this->max);
      else throw new Exception('Validator needs some initialization');
    }
  public function init($options){
    parent::init($options);
    $this->min = $this->getOption('min', -1);
    $this->max = $this->getOption('max', -1);
  }
  public function isValid($value) {
    $result = TRUE;
    if(($this->max > -1) && (mb_strlen($value) > $this->max)) $result = FALSE;
    if(($this->min > -1) && (mb_strlen($value) < $this->min)) $result = FALSE;
    if(!$result)
      $this->errorMessages[] = $this->provideErrorMessage($value);
    return $result;
  }
  public function getHTMLTagAttributes() {
    $return = array();
    if(($this->min > -1)) $return['minlength'] = array($this->min);
    if(($this->max > -1)) $return['maxlength'] = array($this->max);
    return $return;
  }
}

